#!/usr/bin/env python2

from ConfigParser import ConfigParser
import sys
import os

s3cfg = os.path.join(os.getenv('HOME'), '.s3cfg')
key = 'AWS_ACCESS_KEY_ID'
secret = 'AWS_SECRET_ACCESS_KEY'

def die(code, *args):
    sys.stderr.write(' '.join(["ERROR "] + list(args)) + '\n');
    sys.exit(code)

def get_keys():
    config = ConfigParser()
    config.read(s3cfg)
    aws_key = config.get('default', 'access_key')
    aws_secret = config.get('default', 'secret_key')

    return (aws_key, aws_secret)

def get_shell():
    return os.path.basename(os.getenv('SHELL', '/bin/sh'))

def export():
    aws_key, aws_secret = get_keys()

    if (get_shell() == 'fish'):
        print('set -e', key, '; set -x -U', key, aws_key)
        print('set -e', secret, '; set -x -U', secret, aws_secret)
        return

    print('export {}={}'.format(key, aws_key))
    print('export {}={}'.format(secret, aws_secret))

def check_s3cfg():
    if not os.path.exists(s3cfg):
        # $ cat /usr/include/sysexits.h
        # define EX_CONFIG       78      /* configuration error */
        die(78, s3cfg, 'not found')

def main():
    check_s3cfg()
    export()

if __name__ == '__main__':
    main()
